package com.inight.nightojbackendjudgeservice.rabbitmq;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

/**
 * MQ 只需要在项目启动之后, 启动一次即可
 */
@Slf4j
public class InitRabbitMQ {

    /**
     * 用于创建测试程序用到的交换机和队列（只用在程序启动前执行一次）
     */
    public static void doInitRabbitMQ() {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            // 设置地址
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel(); // 相当于rabbitMQ 的客户端, 类似 redisTemplate
            // 设置交换机
            String EXCHANGE_NAME = "code_exchange";
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            // 创建队列，随机分配一个队列名称
            String queueName = "code_queue";
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, EXCHANGE_NAME, "my_routingKey");
        } catch (Exception e) {
            log.error("Error in initRabbitMQ: 消息队列启动失败  ", e);
        }
    }

    public static void main(String[] args) {
        doInitRabbitMQ();
    }

}
